/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.app.utill;

import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * PixelMapUtil
 *
 * @since 2021-05-17
 */
public class PixelMapUtil {
    private static HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x000001, "PixelMapUtil");

    /**
     * 根据图片资源id获取PixelMap
     *
     * @param context context
     * @param resourceId resourceId
     * @return 图片的PixelMap
     */
    public static Optional<PixelMap> getPixelMapFromResource(Context context, int resourceId) {
        InputStream inputStream = null;
        ImageSource imageSource = null;
        ImageSource.DecodingOptions decodingOptions = null;
        try {
            // 创建图像数据源ImageSource对象
            inputStream = context.getResourceManager().getResource(resourceId);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/jpg";
            imageSource = ImageSource.create(inputStream, srcOpts);

            // 设置图片参数
            decodingOptions = new ImageSource.DecodingOptions();
        } catch (IOException e) {
            HiLog.info(label, "IOException");
        } catch (NotExistException e) {
            HiLog.info(label, "NotExistException");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    HiLog.info(label, "inputStream IOException");
                }
            }
        }

        if (imageSource != null && decodingOptions != null) {
            return Optional.ofNullable(imageSource.createPixelmap(decodingOptions));
        }
        return Optional.empty();
    }
}
